package consul

import (
	"fmt"

	"github.com/hashicorp/consul/api"
)

type Register interface {
	RegisterService(serviceName string, ip string, port int, tags []string) error
	DeregisterService(serviceID string) error
}

type Consul struct {
	client *api.Client
}

func NewConsulRegister(addr string) (Register, error) {
	cfg := api.DefaultConfig()
	cfg.Address = addr
	c, err := api.NewClient(cfg)
	if err != nil {
		return nil, err
	}
	return &Consul{c}, nil
}

// RegisterService 将web服务注册到consul
func (c *Consul) RegisterService(serviceName string, ip string, port int, tags []string) error {
	// 健康检查
	check := &api.AgentServiceCheck{
		HTTP:                           fmt.Sprintf("http://%s:%d/health", ip, port), // 这里一定是外部可以访问的地址
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "15s",
	}
	srv := &api.AgentServiceRegistration{
		ID:      fmt.Sprintf("%s-%s-%d", serviceName, ip, port), // 服务唯一ID
		Name:    serviceName,                                    // 服务名称
		Tags:    tags,                                           // 为服务打标签
		Address: ip,
		Port:    port,
		Check:   check,
	}
	return c.client.Agent().ServiceRegister(srv)
}

// DeregisterService 注销服务
func (c *Consul) DeregisterService(serviceID string) error {
	err := c.client.Agent().ServiceDeregister(serviceID)
	if err != nil {
		return err
	}
	return nil
}
